package com.tuyan.aixiang.activity.login;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.tuyan.aixiang.api.HttpClient;
import com.tuyan.aixiang.api.helper.ResultTransformer;
import com.tuyan.aixiang.api.helper.RxSchedulers;
import com.tuyan.aixiang.common.AppData;
import com.tuyan.aixiang.common.BasePresenter;
import com.tuyan.aixiang.common.M;
import com.tuyan.aixiang.model.UserInfo;
import com.tuyan.aixiang.util.ToastUtil;

import io.reactivex.disposables.Disposable;

public class LoginPresenter extends BasePresenter<LoginActivity> implements Login.Presenter {


    @Override
    public void doLogin(String username, String password) {
        M m = M.m().put("dr_login_account", username).put("dr_login_pass", password);
        iView.get().showLoading();
        Disposable disposable = HttpClient.getAccount().login(m).compose(RxSchedulers.io_main()).compose(ResultTransformer.handleResult())
                .subscribe(data -> {
                    iView.get().hideLoading();
                    if (null != data) {
                        JsonObject info = data.get().getAsJsonObject();
                        UserInfo userInfo = new Gson().fromJson(info, UserInfo.class);
                        AppData.setUserInfo(userInfo);
                        iView.get().loginSuccess();
                    }
                }, throwable -> {
                    iView.get().hideLoading();
                    ToastUtil.makeShort(throwable.getMessage());
                });
        addDisposable(disposable);

    }
}
